import Route from '@/utils/Route.js';
import Tools from '@/utils/Tools.js';
let domain = 'https://yz.qzyzjk.com/';
const get = (url, data, success, fail, complete, check_login) => {
	uni.showNavigationBarLoading();
	let that = this;
	data = data || {};
	data.wxapp_id = Tools.getWxappId();

	let request = () => {
		data.token = uni.getStorageSync('token');
		uni.request({
			url,
			header: {
				'content-type': 'application/json'
			},
			data: data,
			success(res) {
				if (res.statusCode !== 200 || typeof res.data !== 'object') {
					console.log(res);
					Tools.showError('网络请求出错');
					return false;
				}
				if (res.data.code === -1) {
					// 登录态失效, 重新登录
					wx.hideNavigationBarLoading();
					doLogin();
				} else if (res.data.code === 0) {
					Tools.showError(res.data.msg, () => {
						fail && fail(res);
					});
					return false;
				} else {
					success && success(res.data);
				}
			},
			fail(res) {
				report(res, url, data)
				Tools.showError(res.errMsg, () => {
					fail && fail(res);
				});
			},
			complete(res) {
				wx.hideNavigationBarLoading();
				complete && complete(res);
			},
		});
	};
	// 判断是否需要验证登录
	check_login ? doLogin(request) : request();
}

const post = (url, data, success, fail, complete, isShowNavBarLoading) => {
	isShowNavBarLoading || true;
	data.wxapp_id = Tools.getWxappId();
	data.token = wx.getStorageSync('token');
	// 在当前页面显示导航条加载动画
	if (isShowNavBarLoading == true) {
		uni.showNavigationBarLoading();
	}
	uni.request({
		url,
		header: {
			'content-type': 'application/x-www-form-urlencoded',
		},
		method: 'POST',
		data: data,
		success(res) {
			if (res.statusCode !== 200 || typeof res.data !== 'object') {
				if (fail) {
					fail(res);
				} else {
					Tools.showError('网络请求出错');
				}
				return false;
			}
			if (res.data.code === -1) {
				// 登录态失效, 重新登录
				uni.hideNavigationBarLoading();
				doLogin();
				return false;
			} else if (res.data.code === 0) {
				Tools.showError(res.data.msg, () => {
					fail && fail(res);
				});
				return false;
			}
			success && success(res.data);
		},
		fail(res) {
			// console.log(res);
			report(res, url, data, 'HttpPostError')
			Tools.showError(res.errMsg, () => {
				fail && fail(res);
			});
		},
		complete(res) {
			uni.hideNavigationBarLoading();
			// wx.hideLoading();
			complete && complete(res);
		}
	});
}

const report = (error, url = '', data = {}, eventName = 'HttpGetError') => {
	setTimeout(() => {
		try {
			const error = {
				token: uni.getStorageSync('token') || '',
				user_id: uni.getStorageSync('user_id') || '',
				error,
				url,
				data
			};
			uni.report(eventName, error);
		} catch (e) {
			//TODO handle the exception
		}

	}, 0)
}
const upload = (url, filePath, fileKey, params, success, fail, complete, isShowNavBarLoading) => {
	params.wxapp_id = Tools.getWxappId();
	params.token = wx.getStorageSync('token');
	uni.uploadFile({
		url,
		filePath: filePath,
		name: 'iFile',
		formData: params,
		success: (res) => {
			res = (typeof res.data === 'object' ? res.data : JSON.parse(res.data));
			if (res.code === 1) {
				success && success(res);
			}
		},
		fail: (res) => {
			// console.log(res);
			Tools.showError(res.errMsg, () => {
				fail && fail(res);
			});
		},
		complete: () => {
			uni.hideNavigationBarLoading();
			// wx.hideLoading();
			complete && complete();
		}
	});
}

const link = (url, data) => {
	console.log(data)
	data = data || {};
	data.wxapp_id = Tools.getWxappId();

	data.token = uni.getStorageSync('token');
	return url + '&' + Tools.urlEncode(data)
	// for (let item of data) {
	// 	console.log(item)

	// 	dataArray.push(item + '=' + data[item])
	// }
	// return url + '?' + dataArray.join('&');
}

/**
 * 执行用户登录
 */
const doLogin = () => {
	// 保存当前页面
	let pages = getCurrentPages();
	if (pages.length) {
		let currentPage = pages[pages.length - 1];
		"pages/login/index" != currentPage.route &&
			uni.setStorageSync("currentPage", {
				route: currentPage.route,
				params: Tools.urlEncode(currentPage.options)
			});
	}
	Route.toLogin()

};
/**
 * 记录formId
 */
const saveFormId = (formId) => {
	console.log('saveFormId');
	if (formId === 'the formId is a mock one' || !formId) {
		return false;
	}

	setTimeout(() => {
		post(api.saveWxappFormId, {
			formId: formId,
		}, null, null, null, false)
	}, 0)
}

const api = {
	loginMP: domain + '/index.php?s=/api/wxapp/wxapp_login',
	saveWxappFormId: domain + '/index.php?s=/api/wxapp.formId/save',
	getCategoryList: domain + '/index.php?s=/api/category/routine_category',
	getRecommendGoodsList: domain + '/index.php?s=/api/goods/recommend_goods',
	getGoodsDetail: domain + '/index.php?s=/api/goods/detail',
	getNickName: domain + '/index.php?s=/api/user/nickName',
	sendCode: domain + '/index.php?s=/api/identify/send',
	regForPhone: domain + '/index.php?s=/api/user/phone_reg',
	getUserInfo: domain + '/index.php?s=/api/user/detail',
	getUserDetail: domain + '/index.php?s=/api/user.index/detail',
	loginForPassword: domain + '/index.php?s=/api/user/password_login',
	addCart: domain + '/index.php?s=/api/cart/add',
	getCart: domain + '/index.php?s=/api/cart/lists',
	delCart: domain + '/index.php?s=/api/cart/delete',
	subCart: domain + '/index.php?s=/api/cart/sub',
	buyNow: domain + '/index.php?s=/api/order/buyNow',
	orderCart: domain + '/index.php?s=/api/order/cart',
	addAddress: domain + '/index.php?s=/api/address/add',
	getCouponList: domain + '/index.php?s=/api/coupon/lists',
	receiveUserCoupon: domain + '/index.php?s=/api/user.coupon/receive',
	getCategory: domain + '/index.php?s=/api/category/index',
	getGoodsList: domain + '/index.php?s=/api/goods/lists',
	getAddressList: domain + '/index.php?s=/api/address/lists',
	delAddress: domain + '/index.php?s=/api/address/delete',
	setDefaultAddress: domain + '/index.php?s=/api/address/setDefault',
	getAddressDetail: domain + '/index.php?s=/api/address/detail',
	editAddress: domain + '/index.php?s=/api/address/edit',
	getuserCouponLists: domain + '/index.php?s=/api/user.coupon/lists',
	getWxappHelp: domain + '/index.php?s=/api/wxapp/help',
	getUserWallet: domain + '/index.php?s=/api/user.wallet/index',
	getUserOrderLists: domain + '/index.php?s=/api/user.order/lists',
	cancelUserOrder: domain + '/index.php?s=/api/user.order/cancel',
	payUserOrder: domain + '/index.php?s=/api/user.order/pay',
	receiptUserOrder: domain + '/index.php?s=/api/user.order/receipt',
	getUserOrderDetail: domain + '/index.php?s=/api/user.order/detail',
	getShopLists: domain + '/index.php?s=/api/shop/lists',
	getUserOrderExtractQrcode: domain + '/index.php?s=/api/user.order/extractQrcode',
	getShopDetail: domain + '/index.php?s=/api/shop/detail',
	userCommentOrder: domain + '/index.php?s=/api/user.comment/order',
	uploadImage: domain + '/index.php?s=/api/upload/image',
	getGoodsPoster: domain + '/index.php?s=/api/goods/poster',
	applyUserRefund: domain + '/index.php?s=/api/user.refund/apply',
	getUserRefundLists: domain + '/index.php?s=/api/user.refund/lists',
	getUserRefundDetail: domain + '/index.php?s=/api/user.refund/detail',
	saveUserRefundDelivery: domain + '/index.php?s=/api/user.refund/delivery',
	getCommentLists: domain + 'index.php?s=/api/comment/lists',
	getUserDealerCenter: domain + 'index.php?s=/api/user.dealer/center',
	getUserDealerWithdraw: domain + 'index.php?s=/api/user.dealer/withdraw',
	submitUserDealerWithdraw: domain + 'index.php?s=/api/user.dealer.withdraw/submit',
	getUserDealerWithdrawLists: domain + 'index.php?s=/api/user.dealer.withdraw/lists',
	getUserDealerQrcodePoster: domain + 'index.php?s=/api/user.dealer.qrcode/poster',
	getRechargeIndex: domain + 'index.php?s=/api/recharge/index',
	submitRecharge: domain + 'index.php?s=/api/recharge/submit',
	getBalanceLogLists: domain + 'index.php?s=/api/balance.log/lists',
	getPage: domain + 'index.php?s=/api/page/index',
	getArticleDetail: domain + 'index.php?s=/api/article/detail',
	logout: domain + 'index.php?s=/api/user/logout',
	getShopOrderDetail: domain + 'index.php?s=/api/shop.order/detail',
	shopOrderExtract: domain + 'index.php?s=/api/shop.order/extract',
	getUserDealerTeamLists: domain + 'index.php?s=/api/user.dealer.team/lists',
	getUserDealerOrderLists: domain + 'index.php?s=/api/user.dealer.order/lists',
	getWxConfig: domain + 'index.php?s=/api/wechat/getWxConfig',
	getWechatCode: domain + 'index.php?s=/api/wechat/getCode',
	loginWithWechatCode: domain + 'index.php?s=/api/wechat/codeLogin',
	getUserAgentCenter: domain + 'index.php?s=/api/user.agent/center',
	getUserAgentOrderLists: domain + 'index.php?s=/api/user.agent.order/lists',
	getUserAgentWithdrawLists: domain + 'index.php?s=/api/user.agent.withdraw/lists',
	getUserAgentWithdraw: domain + 'index.php?s=/api/user.agent/withdraw',
	getUserAgentWithdrawSubmit: domain + 'index.php?s=/api/user.agent.withdraw/submit',
	getSnsInfo: domain + 'index.php?s=/api/sns/snsInfo',
	unbindWechatAuth: domain + 'index.php?s=/api/wechat/unbind',
	saveBaseInfo: domain + 'index.php?s=/api/user/saveBaseInfo',
	forgetPassword: domain + 'index.php?s=/api/user/forget',
	checkPhoneAccount: domain + 'index.php?s=/api/user/phoneAccountCheck',
	loginByThirdId: domain + 'index.php?s=/api/user/loginByThirdId',
	getSharingIndex: domain + 'index.php?s=/api/sharing.index/index',
	getSharingGoodsList: domain + 'index.php?s=/api/sharing.goods/lists',
	getSharpIndex: domain + 'index.php?s=/api/sharp.index/index',
	getSharpGoodsLists: domain + 'index.php?s=/api/sharp.goods/lists',
	getSharpGgoodsDetail: domain + 'index.php?s=/api/sharp.goods/detail',
	checkoutSharpOrder: domain + 'index.php?s=/api/sharp.order/checkout',
	getRechargeOrderLists: domain + 'index.php?s=/api/recharge.order/lists',
	getBargainActiveDetail: domain + 'index.php?s=/api/bargain.active/detail',
	postBargainTaskPartake: domain + 'index.php?s=/api/bargain.task/partake',
	getBargainTaskDetail: domain + 'index.php?s=/api/bargain.task/detail',
	checkoutBargainOrder: domain + 'index.php?s=/api/bargain.order/checkout',
	getBargainActivePoster: domain + 'index.php?s=/api/bargain.active/poster',
	helpCutBargainTask: domain + 'index.php?s=/api/bargain.task/help_cut',
	getBargainTaskLists: domain + 'index.php?s=/api/bargain.task/lists',
	getBargainActiveLists: domain + 'index.php?s=/api/bargain.active/lists',
	getAllSharingSetting: domain + 'index.php?s=/api/sharing.setting/getAll',
	getSharingGoodsDetail: domain + 'index.php?s=/api/sharing.goods/detail',
	getSharingGoodsPoster: domain + 'index.php?s=/api/sharing.goods/poster',
	getSharingActiveDetail: domain + 'index.php?s=/api/sharing.active/detail',
	checkoutSharingOrder: domain + 'index.php?s=/api/sharing.order/checkout',
	getSharingOrderLists: domain + 'index.php?s=/api/sharing.order/lists',
	paySharingOrder: domain + 'index.php?s=/api/sharing.order/pay',
	receiptSharingOrder: domain + 'index.php?s=/api/sharing.order/receipt',
	cancelSharingOrder: domain + 'index.php?s=/api/sharing.order/cancel',
	getSharingOrderDetail: domain + 'index.php?s=/api/sharing.order/detail',
	applySharingRefund: domain + 'index.php?s=/api/sharing.refund/apply',
	getSharingRefundLists: domain + 'index.php?s=/api/sharing.refund/lists',
	getSharingRefundDetail: domain + 'index.php?s=/api/sharing.refund/detail',
	postSharingRefundDelivery: domain + 'index.php?s=/api/sharing.refund/delivery',
	getSharingOrderExpress: domain + 'index.php?s=/api/sharing.order/express',
	sharingCommentOrder: domain + 'index.php?s=/api/sharing.comment/order',
	getUserOrderExpress: domain + 'index.php?s=/api/user.order/express',
	getSharingCommentLists: domain + 'index.php?s=/api/sharing.comment/lists',
	getSharpGoodsPoster: domain + 'index.php?s=/api/sharp.goods/poster',
	getParameterTel: domain + 'index.php?s=/api/parameter/tel',
	getPointsLog: domain + 'index.php?s=/api/points.log/index',
	checkRefereeCode: domain + 'index.php?s=/api/user/checkRefereeCode',
	submitWithdraw: domain + 'index.php?s=/api/user.withdraw/submit',
	settingWithdraw: domain + 'index.php?s=/api/user.withdraw/setting',
	getUserWithdrawLists: domain + 'index.php?s=/api/user.withdraw/lists',


}

export default {
	api,
	get,
	post,
	upload,
	link,
	saveFormId
}
